package com.tenton.servlet;

import com.tenton.pojo.User;
import com.tenton.service.Impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Date: 2021/1/12
 * @Author: Tenton
 * @Description: 用户登录
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        UserServiceImpl userServiceImpl = new UserServiceImpl();
        List<User> users = userServiceImpl.listUser();
        //获取表单元素
        //用户名
        String userName = request.getParameter("userName");
        //密码
        String password = request.getParameter("password");
        //验证码
        String vericode = request.getParameter("vericode");
        String generatedCode= (String) request.getSession().getAttribute("verityCode");
        boolean flag = false;
        for (User user : users) {
            if (user.getUserName().equals(userName) && user.getPassword().equals(password) && vericode.toLowerCase().equals(generatedCode.toLowerCase())) {
                flag = true;
            }
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前系统时间
        String format = df.format(new Date());
        if (flag){
            //增加用户登录信息到redis中
            userServiceImpl.addRedisLog(userName,format,"登录成功");
            //登录用户
            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            request.getSession().setAttribute("user", user);
        }else {
            response.getWriter().write("用户名或密码错误，2秒后自动跳转到登陆界面");
            response.setHeader("Refresh","3;URL=login.jsp");
        }
        //如果用户勾选过30天内自动登陆,发送自动登陆cookie
        if("true".equals(request.getParameter("autologin"))){
            Cookie autologinC = new Cookie("autologin",userName+":"+password);
            autologinC.setPath(request.getContextPath());
            autologinC.setMaxAge(3600*24*30);
            response.addCookie(autologinC);
        }
        //请求跳转到主界面
        request.getRequestDispatcher("/listUserServlet").forward(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
